import { getNewField } from '@/management/utils'
import { cloneDeep as _cloneDeep, get as _get } from 'lodash-es'
import { get as getFormById } from '@/management/api/dataform'
import { termPurviewList, purviewList } from '@/management/api/dataform-extend'
import { FormType } from '@/management/utils/types/formsTypes';

export default {
  async init({ state, dispatch }) {
    const metaData = _get(state, 'schema.metaData')
    if (!metaData || metaData._id !== state.formId) {
      await dispatch('getSchemaFromRemote')
    } 
    dispatch('resetState')
  },
  async getSchemaFromRemote({ commit, state }) {
    const res = await getFormById(state.formId)
    let members = []
    try {
      const respon = await purviewList({condition: {formId: state.formId}})
      // console.log('respon', respon)
      if (respon?.serverResult?.resultCode === '200') {
        members = respon?.result?.list || []
      } else {
        members = []
      }
      // console.log('members', members)
    } catch (err) {
      console.log(err)
    }
    let collaborator = []
    try {
      const resp = await termPurviewList({condition: {formId: state.formId}})
      // console.log('resp', resp)
      if (resp?.serverResult?.resultCode === '200') {
        collaborator = resp?.result?.list || []
      } else {
        collaborator = []
      }
      // console.log('collaborator', collaborator)
    } catch (err) {
      console.log(err)
    }

    if (res?.result?.formId) {
      const schema = res.result.skinConf ? JSON.parse(res.result.skinConf) : {}

      const metaData = {
        ...res.result,
        "_id": res.result.formId,
        "createDate": res.result.createTime,
        "updateDate": res.result.lastModifyTime,
        "title": res.result.formName || '调研活动',
        "remark": res.result.formRemark,
        "surveyType": res.result.formType,
        "surveyPath": res.result.formId,
        "creatorName": res.result.creatorName || 'admin',
        "owner": res.result.creatorName || 'admin',
        "ownerId": res.result.creatorId,
        "createMethod": "basic",
        "currentUserId": res.result.creatorId,
        "isCollaborated": false
      }
      document.title = metaData.title
      const bannerConf = _get(schema, 'bannerConf', {
        "titleConfig": {
          "mainTitle": res.result.formRemark || "<h3 style=\"text-align: center\">欢迎填写问卷</h3><p>为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，<span style=\"color: rgb(204, 0, 0)\">期待您的参与！</span></p>",
          "subTitle": res.result.formName || ''
        },
        "bannerConfig": {
          "bgImage": "/myactivity/imgs/skin/17e06b7604a007e1d3e1453b9ddadc3c.webp",
          "videoLink": "",
          "postImg": ""
        }
      })
      const bottomConf = _get(schema, 'bottomConf', {
        "logoImage": "",
        "logoImageWidth": "60%"
      })
      const baseConf = _get(schema, 'baseConf', {
        "begTime": res.result.startTime,
        "endTime": res.result.endTime,
        "tLimit": 0,
        "answerLimitTime": 0,
        "isMultiple": true,
        "anonymous": true,
        "isUpdate": true,
        "isDel": true,
        "isTop": true,
        "language": "chinese",
        "answerBegTime": "00:00:00",
        "answerEndTime": "23:59:59",
        "answerUser": [],
        "adminUser": []
      })
      const skinConf = _get(schema, 'skinConf', {
        "skinColor": "#4a4c5b",
        "inputBgColor": "#ffffff",
        "backgroundConf": {
          "color": "#fff"
        },
        "themeConf": {
          "color": "#0081fa"
        },
        "contentConf": {
          "opacity": 100
        }
      })
      const submitConf = _get(schema, 'submitConf', {
        "submitTitle": "提交",
        "confirmAgain": {
          "is_again": false,
          "again_text": "确认要提交吗？"
        },
        "msgContent": {
          "msg_200": "提交成功",
          "msg_9001": "您来晚了，感谢支持问卷~",
          "msg_9002": "请勿多次提交！",
          "msg_9003": "您来晚了，已经满额！",
          "msg_9004": "提交失败！"
        }
      })
      const logicConf = _get(schema, 'logicConf', {
        "showLogicConf": []
      }) 
      const dataConf = _get(schema, 'dataConf', {
        "dataList": []
      })

      if (res.result.formType === FormType.System || window?.$ui?.urlQuery?.tid) {
        baseConf.begTime = ''
        baseConf.endTime = ''
        baseConf.anonymous = true
        baseConf.answerUser = []
        baseConf.adminUser = []
        metaData.useLimit = ''
        metaData.answerUser = []
        metaData.adminUser = []
        console.log('系统问卷', baseConf)
      } else {
        if (members.length === 0) {
          baseConf.anonymous = true
          baseConf.answerUser = []
          metaData.answerUser = []
        }
        if (collaborator.length === 0) {
          baseConf.adminUser = []
          metaData.adminUser = []
        }
      }
      // console.log(state.schema)
      // console.log(window?.$ui?.urlQuery?.tid)
      commit('initSchema', {
        metaData,
        codeData: {
          bannerConf,
          bottomConf,
          skinConf,
          baseConf,
          submitConf,
          questionDataList: dataConf.dataList,
          logicConf
        }
      })
    } else {
      throw new Error(res?.serverResult?.resultMessage || '活动不存在')
    }
  },

  resetState({ commit }) {
    commit('setCurrentEditOne', null)
    commit('changeStatusPreview', { type: 'Success' })
  },
  // 复制问题到当前问题后
  copyQuestion({ commit, state }, { index }) {
    const newQuestion = _cloneDeep(state.schema.questionDataList[index])
    newQuestion.field = getNewField(state.schema.questionDataList.map((item) => item.field))
    commit('addQuestion', { question: newQuestion, index })
  },
  addQuestion({ commit }, { question, index }) {
    commit('addQuestion', { question, index })
    commit('updateSchemaUpdateTime', Date.now())
  },
  deleteQuestion({ commit }, { index }) {
    commit('deleteQuestion', { index })
    commit('updateSchemaUpdateTime', Date.now())
  },
  moveQuestion({ commit }, { index, range }) {
    commit('moveQuestion', { index, range })
    commit('updateSchemaUpdateTime', Date.now())
  },
  changeSchema({ commit }, { key, value }) {
    commit('changeSchema', { key, value })
    commit('updateSchemaUpdateTime', Date.now())
  },
  changeThemePreset({ commit }, presets) {
    commit('changeThemePreset', presets)
  },

  updataQuestionList({ commit }, data) {
    commit('updataQuestionList', data)
  },
}
